<?php


/**
 * @author fyl
 * Date: 16-3-29 下午2:59
 */

class IndexService extends BaseService
{
    private static $self       =   NULL;
    private $mAdmin             =  NULL;
    private $mAds               =  NULL;
    private $mLog               =  NULL;
    private $mProject           =  NULL;
    private $mInvestRecord      =  NULL;
    private $mTicketRecord      =  NULL;
    private $mRechargeRecord    =  NULL;
    private $mWithdrawRecord    =  NULL;
    private $mBankManage        =  NULL;
    private $mUser              =  NULL;
    private $mNews              =  NULL;
    private $mAbutPartner       =  NULL;
    private $mAbutTeam          =  NULL;
    private $mAbutRecruit       =  NULL;
    private $mCompany           =  NULL;
    private $mUserExtend        =  NULL;



    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }


    public function __construct()
    {
        $this->mAdmin             =   new Involved_AdminModel();
        $this->mAds               =   new Involved_AdsModel();
        $this->mLog               =   new Involved_LogModel();
        $this->mProject           =   new Involved_ProjectModel();
        $this->mInvestRecord      =   new Involved_InvestRecordModel();
        $this->mTicketRecord      =   new Involved_TicketRecordModel();
        $this->mRechargeRecord    =   new Involved_RechargeRecordModel();
        $this->mWithdrawRecord    =   new Involved_WithdrawRecordModel();
        $this->mBankManage        =   new Involved_BankManageModel();
        $this->mUser              =   new Involved_UserModel();
        $this->mNews              =   new Involved_NewsModel();
        $this->mAbutPartner       =   new Involved_AbutPartnerModel();
        $this->mAbutTeam          =   new Involved_AbutTeamModel();
        $this->mAbutRecruit       =   new Involved_AbutRecruitModel();
        $this->mCompany           =   new Involved_CompanyModel();
        $this->mUserExtend        =   new Involved_UserExtendModel();
    }


    /**
     * 登陆验证
     * @param $user
     * @return mixed
     * @throws Exception
     */
    public function VerifyLogin($user)
    {
        #此处只做简单验证
        if(empty($user->username) || empty($user->password)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #数据验证
        $user_info = $this->mUser->getUserInfo($user->username,md5($user->password));

        if(!$user_info){
            throw new Exception('用户名或密码错误', ProfessionErrorCodeEnum::ERROR_PASSWORD_WRONG);
        }
        #存储SESSION

        if(preg_match('/^1[34578]\d{9}$/',$user->username)){
            Session::put(UserEnum::USER_INFO_USER_NAME, $user_info->mobile);
        }else{
            Session::put(UserEnum::USER_INFO_USER_NAME, $user_info->user_name);
        }
        Session::put(UserEnum::USER_INFO_USER_ID, $user_info->user_id);
        Session::put(UserEnum::USER_INFO_SESSION_KEY, $user_info);
        return $user_info;
    }

    /**
     * 验证用户名
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckUser($paramObj)
    {
        return $this->mUser->JsCheckUser($paramObj->username);
    }

    /**
     * 验证密码
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckPwd($paramObj)
    {
        return $this->mUser->JsCheckPwd($paramObj->username,md5($paramObj->pwd));
    }

    /**
     * 注册验证
     * @param $paramObj
     * @return int
     * @throws Exception
     */
    public function VerifyRegister($paramObj)
    {
        #参数验证
        if(empty($paramObj->user_name) || empty($paramObj->pwd) || empty($paramObj->mobile) || empty($paramObj->captcha)){
            throw new Exception('必填项不能为空', ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #手机号验证
        if (!preg_match('/^1[34578]\d{9}$/', $paramObj->mobile)) {
            throw new Exception("手机号码错误", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }

        #手机号是否已注册
        $mobile = $this->mUser->JsCheckMobile($paramObj->mobile);
        if ($mobile) {
            throw new Exception("手机号已注册", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #验证码
        if(strtolower($paramObj->captcha) != strtolower(Session::get('ypt_Captcha'))){
            throw new Exception('验证码错误', ProfessionErrorCodeEnum::ERROR_VERIFICATION_CODE_WRONG);
        }
        #注册用户
        $aData = [
            'user_name'          =>     $paramObj->user_name,
            'password'           =>     md5($paramObj->pwd),
            'mobile'             =>     $paramObj->mobile,
            'avatar'             =>     './resource/img/user_img.png',
        ];
        if(!empty($paramObj->invite_mobile))
            $aData['invite_mobile'] = $paramObj->invite_mobile;

      $user_id = $this->mUser->insert($aData);

      if($user_id)
          return $this->mUserExtend->insert(['user_id'=>$user_id]);


    }

    /**
     * js验证用户名
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckUserName($paramObj)
    {
        return $this->mUser->JsCheckUsername($paramObj->username);
    }

    /**
     * 验证手机号
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckMobile($paramObj)
    {
        return $this->mUser->JsCheckMobile($paramObj->mobile);
    }

    public function JsCheckCaptcha($paramObj)
    {
        if(strtolower($paramObj->captcha) == strtolower(Session::get('ypt_Captcha'))){
            return 1;
        }else{
            return 2;
        }
    }

    /**
     * 验证邀请人手机号
     * @param $paramObj
     * @return mixed
     */
    public function JsCheckInvite($paramObj)
    {
        return $this->mUser->JsCheckInvite($paramObj->invite_mobile);
    }


    /**
     * 发送短信验证
     * @param $paramObj
     * @return string
     */
    public function VerifyNews($paramObj)
    {

        #接受参数
        $aData["mobile"] = $paramObj->mobile;
        #生成随机验证码
        $news_captcha = substr(str_shuffle("012345678901234567890123456789"), 0, 6);
        #发送参数
        $data = $this->mLog->sendTemplateSMS($paramObj->mobile,array($news_captcha,'5'),1);
        if($data == 10000){
            $aData['time'] = time();
            $aData['news_captcha'] = $news_captcha;
            Session::put(UserEnum::CLIENT_NEWS_CAPTCHA,$aData);
        }

        return $data;
    }

    /**
     * 短信验证
     * @param $paramObj
     * @return int
     */
    public function JsCheckNews($paramObj)
    {
        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        $time =time()-$info['time'];
        if($info['news_captcha'] == $paramObj->news_captcha && $info['mobile'] == $paramObj->mobile){
            if($time<=300){
                return 1;
            }else{
                return 2;
            }
        }else{
            return  3;
        }
    }

    public function JsVerifyUserNews($paramObj)
    {
        $info =session_get(UserEnum::CLIENT_NEWS_CAPTCHA);
        $time =time()-$info['time'];
        if($info['news_captcha'] == $paramObj->news_captcha)
        {
            if($time<=300){
                return 1;
            }else{
                return 2;
            }
        }else{}
    }

    /**
     * 忘记密码验验证
     * @param $paramObj
     * @return int
     */
    public function JsVerifyUserCaptcha($paramObj)
    {
        if(strtolower($paramObj->captcha) != strtolower(Session::get('ypt_Captcha'))) {
            return 2;
        }
    }

    /**
     * 忘记密码手机验证
     * @param $paramObj
     * @return int
     */
    public function JsVerifyUserMobile($paramObj)
    {
        return $this->mUser->JsVerifyUserMobile($paramObj->mobile);
    }

    /**
     * 忘记密码手机验证
     * @param $paramObj
     * @return mixed
     * @throws Exception
     */
    public function VerifyUserMobile($paramObj)
    {
        #验证码
        if(strtolower($paramObj->captcha) != strtolower(Session::get('ypt_Captcha'))){
            throw new Exception('验证码错误', ProfessionErrorCodeEnum::ERROR_VERIFICATION_CODE_WRONG);
        }
        return $this->mUser->JsVerifyUserMobile($paramObj->mobile);
    }






    /**
     * 广告位列表
     */
    public function AdsList()
    {
        return $this->mAds->AdsList();
    }

    /**
     * 用户列表
     * @return mixed
     */
    public function ManageUser()
    {
        return $this->mUser->ManageUserList();

    }


    /**
     * 项目央票通列表
     */
    public function YptProjectList($project_id=null){
        if(empty($project_id)and empty($type)){
            $list = $this->mProject->YptProjectList($project_id);
            $company_name = $this->Relevance($list,'company_name'); //获取公司名称数组
            $companylist = $this->mCompany->CompanyList($company_name);//获取公司列表
            $company = $this->VelToKey($companylist,'company_name');
            //获取项目已投资金额
            $all_prpject_id = $this->Relevance($list,'project_id'); //获取项目名称数组
            $already_money = $this->mInvestRecord->AlreadyMoney($all_prpject_id);//根据ID获取项目投资金额
            $already = $this->VelToKey($already_money,'project_id');
            foreach($list as &$v){
                if(isset($company)){
                    $v->rank = $company[$v->company_name]->rank;
                    $v->logo_img = $company[$v->company_name]->logo;
                    if(empty($already[$v->project_id])){
                        $v->percentage = "0%";
                    }else{
                        $v->percentage = number_format($already[$v->project_id]->money/$v->project_scale*100,2)."%";
                    }
                }
            }
        }else{
            $list = $this->mProject->YptProjectList($project_id);
            $company_name = $this->Relevance($list,'company_name'); //获取公司名称数组
            $companylist = $this->mCompany->CompanyList($company_name);//获取公司列表
            $company = $this->VelToKey($companylist,'company_name');
            //获取项目已投资金额
            $all_prpject_id = $this->Relevance($list,'project_id'); //获取项目ID称数组
            $already_money = $this->mInvestRecord->AlreadyMoney($all_prpject_id);//根据ID获取项目投资金额
            $already = $this->VelToKey($already_money,'project_id');
            //获取合作伙伴信息
            $all_prpject_id = $this->Relevance($list,'partner_id'); //获取项目ID称数组
            $partnerlist = $this->mAbutPartner->GetPartnerId($all_prpject_id);//根据ID获取项目合作商信息
            $partner = $this->VelToKey($partnerlist,'partner_id');
            foreach($list as &$v){
                if(isset($company) and !empty($partner)){
                    $v->rank = $company[$v->company_name]->rank;
                    $v->plate = $company[$v->company_name]->plate;
                    $v->brief = $company[$v->company_name]->brief;
                    $v->stock_num = $company[$v->company_name]->stock_num;
                    $v->partner_id = $partner[$v->partner_id]->partner_name;
                    $v->logo_img = $company[$v->company_name]->logo;
                    if(empty($already[$v->project_id])){
                        $v->percentage = "0%";
                    }else{
                        $v->percentage = number_format($already[$v->project_id]->money/$v->project_scale*100,2)."%";
                    }
                }
            }
        }

        return $list;
    }

    /**
     * 项目上市通列表
     */
    public function SstProjectList(){
        $list = $this->mProject->SstProjectList();
        $company_name = array();
        foreach($list as $v){
            if(!in_array($v->company_name,$company_name)){
                $company_name[] = $v->company_name;
            }
        }
        $companylist = $this->mCompany->CompanyList($company_name);
        $company = $this->VelToKey($companylist,'company_name');

        $all_prpject_id = $this->Relevance($list,'project_id'); //获取公司名称数组
        $already_money = $this->mInvestRecord->AlreadyMoney($all_prpject_id);//根据ID获取项目投资金额
        $already = $this->VelToKey($already_money,'project_id');
        foreach($list as &$v){
            if(isset($companylist)){
                $v->plate = $company[$v->company_name]->plate;
                if(empty($already[$v->project_id])){
                    $v->percentage = "0%";
                }else{
                    $v->percentage = number_format($already[$v->project_id]->money/$v->project_scale*100,2)."%";
                }
            }
        }
        return   $list;

    }

    /**
     * 查询一条项目
     */
            public function SelectOneProject($paramObj){
                $aData =  $paramObj->project_id;
                return $this->mProject->GetProjectOne($aData);
            }

    /**
     * 项目总数
     */
    public function ProjectNum(){
        return $this->mProject->ProjectNum();
    }

    /**
     * 项目总规模
     */
    public function ProjectScale(){
        return $this->mProject->ProjectScale();
    }



    /**
     * 投资记录分页
     */
    public function InvestRecordListPage($project_id,$page){
        $list = $this->mInvestRecord->InvestRecordList($project_id,$page);
        $user_id = $this->Relevance($list,'user_id'); //获取用户ID数组
        if(count($user_id)!=0) {
            $user_list = $this->mUser->UserName($user_id);
            $user = $this->VelToKey($user_list, 'user_id');
            foreach ($list as &$v) {
                $v->user_id = $user[$v->user_id]->user_name;
            }
            $count = $this->mInvestRecord->AllInvestNum($project_id);
            $page_num = ceil($count / HostEnum::PAGE_NUM);
            $pageup = $page - 1 > 1 ? $page - 1 : 1;
            $pagedown = $page + 1 < $page_num ? $page + 1 : $page_num;
            //分页列表
            $page_list = "";
            foreach ($list as $v) {
                if ($v->status == 1) {
                    $status = "<span style='color: green'>已审核<span>";
                } elseif ($v->status == 2) {
                    $status = "<span style='color: orange'>审核中</span>";
                } else {
                    $status = "<span style='color: red'>未审核</span>";
                };
                $page_list .= "<tr><td>$v->user_id</td><td>$v->invest_money</td><td>$status</td><td>" . date('Y-m-d H:i:s', $v->invest_time) . "</td></tr>";
            }
            $page = "";
            $page .= "<li><a href='javascript:void(0);' class='page' data-page=$pageup data-project_id=$project_id><span>←</span></a></li>";
            for ($i = 1; $i <= $page_num; $i++) {
                $page .= "<li><a href='javascript:void(0);' class='page'  data-page=$i data-project_id=$project_id >$i</a></li>";
            }
            $page .= "<li><a href='javascript:void(0);' class='page' data-page=$pagedown data-project_id=$project_id><span>→</span></a></li>";
            $page_all = "<table class='record'><tr><th width='250px;'>投资人</th><th width='220px;'>投资金额（元）</th><th width='260px;'>投资状态</th><th width='244px;'>投资时间</th></tr>$page_list<ul class='pagination'>$page
</ul></table>";
        }else{
            $page_all = "<table class='record'><tr><th width='250px;'>投资人</th><th width='220px;'>投资金额（元）</th><th width='260px;'>投资状态</th><th width='244px;'>投资时间</th></table>";
        }
        return  $page_all;
    }

    /**
     * 查询一条投资记录
     */
    public function SelectOneInvestRecord($paramObj){
        $aData =  $paramObj->invest_id;
        return $this->mInvestRecord->GetInvestRecordOne($aData);
    }

    /**
     * 投资总收益
     */
    public function AllInvestRecord(){
        return $this->mInvestRecord->AllInvestRecord();
    }

    /**
     * 投资总笔数
     */
    public function AllInvestNum(){
        return $this->mInvestRecord->AllInvestNum();
    }


    /**
     * 报票记录列表
     */
    public function TicketRecordList(){
        return $this->mTicketRecord->TicketRecordList();
    }


    /**
     * 充值记录列表
     */
    public function RechargeRecordList(){
        return $this->mRechargeRecord->RechargeRecordList();
    }


    /**
     * 提现记录列表
     */
    public function WithdrawRecordList(){
        return $this->mWithdrawRecord->WithdrawRecordList();
    }


    /**
     * 银行卡列表
     */
    public function BankManageList(){
        return $this->mBankManage->BankManageList();
    }


    /**
     * 首页资讯列表
     * @return mixed
     * hyzx行业资讯 ptxw平台新闻 mtbd媒体报道
     */
    public function NewsIndexList()
    {
        $new = array();
        $new['hyzx'] = $this->mNews->NewsIndexSelect(1,1);
        $new['ptxw'] = $this->mNews->NewsIndexSelect(2,1);
        $new['mtbd'] = $this->mNews->NewsIndexSelect(3,1);

        return $new;
    }

    /**
     * 公告列表
     */
    public function AnnouncementList(){
        return $this->mNews->AnnouncementListSelect(2);
    }


    /**
     * 合作伙伴列表
     * @return mixed
     */
    public function PartnerList()
    {
        return $this->mAbutPartner->PartnerSelect();
    }


    /**
     * 团队列表
     * @return mixed
     */
    public function TeamList()
    {
        return $this->mAbutTeam->TeamSelect();
    }


    /**
     * 招聘列表
     * @return mixed
     */
    public function RecruitList()
    {
        return $this->mAbutRecruit->RecruitSelect();
    }

    /**
     * 将array的每个val转化成key
     */
    public function VelToKey($arr = array(),$key_name){
        $arrRes = array();
        foreach($arr as $k => &$v){
            $arrRes[$v->$key_name] = $arr[$k];
        }
        return $arrRes;
    }

    /**
     * 获取所有关联信息
     */
   public  function Relevance($arr = array(),$name)
   {
       $arrRes = array();
       foreach ($arr as $v) {
           if (!in_array($v->$name, $arrRes)) {
               $arrRes[] = $v->$name;
           }
       }
       return $arrRes;
   }

}